package com.project.fiveCerealsSavoury.controller;


import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.project.fiveCerealsSavoury.domain.Order;
import com.project.fiveCerealsSavoury.domain.OrderState;
import com.project.fiveCerealsSavoury.domain.User;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.IntegrationService;
import com.project.fiveCerealsSavoury.service.OrderService;
import com.project.fiveCerealsSavoury.transfer.AddOrder;

/**
 * 购物车
 * @author Administrator
 *
 */
@Controller
public class ShoppingController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private IntegrationService integrationService; 
	
	@RequestMapping(value="addShopping.do",method=RequestMethod.GET)
	public String addToCat(@Valid @ModelAttribute("addOrder") AddOrder addOrder,BindingResult result,HttpServletRequest request,ModelMap modelMap) throws UnsupportedEncodingException{
		String string = new String(addOrder.getGoodName().getBytes("ISO-8859-1"),"UTF-8");
		User user = (User) request.getSession().getAttribute("USER");
		addOrder.setOrderTime(new Timestamp(new Date().getTime()));
		addOrder.setOrderState(OrderState.已添加到购物车);
		addOrder.setUserId(user.getId());
		addOrder.setGoodName(string);
		try {
			integrationService.addShop(addOrder);
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/shopping.do";
	}
	
	@RequestMapping(value="shopping.do",method=RequestMethod.GET)
	public String shopps(ModelMap modelMap,HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("USER");
		try {
			if(user != null){
				List<Order> queryStatrOrder = orderService.queryStateOrder(user.getId(), OrderState.已添加到购物车);
				modelMap.put("queryStatrOrder", queryStatrOrder);
				return "/good/shoppingCar";
			}
		} catch (Exception e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/good/shoppingCar";
	}
}
